<template>
  <div class="autumn-container">
    <!-- 面包 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="autumn-center">
      <!-- 搜索栏 -->
      <div class="query-form">
        <autumn-search :modelValue="queryInfo" @search="search">
          <template #default>
            <el-form-item prop="code" label="标识">
              <el-input v-model="queryInfo.code" />
            </el-form-item>
            <el-form-item prop="name" label="名称">
              <el-input v-model="queryInfo.name" />
            </el-form-item>
            <el-form-item prop="isEnable" label="启用">
              <el-select v-model="queryInfo.isEnable" placeholder="请选择">
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </template>
        </autumn-search>
      </div>

      <!-- 数据表格 -->
      <div class="main-body top">
        <autumn-table ref="mainTableRef" :page="page" @changePage="changePage" @changeSelect="changeSelect">
          <template #button>
            <el-button type="primary" icon="el-icon-plus" v-if="$hasPermission('system:role:add')" @click="toView">新增
            </el-button>
            <el-button type="info" plain icon="el-icon-user-filled" :disabled="selectNum != 1"
              v-if="$hasPermission('system:role:grant-account')" @click="toUserView">分配用户</el-button>
          </template>
          <template #column>
            <el-table-column type="selection" label="#" fixed="left" align="center" />
            <el-table-column prop="code" label="标识" />
            <el-table-column prop="name" label="名称" />
            <el-table-column label="启用" align="center" width="100">
              <template #default="scope">
                <el-switch v-model="scope.row.isEnable" :active-value="1" :inactive-value="0"
                  :disabled="!$hasPermission('system:role:enable&system:role:disable')"
                  @change="changeEnabled(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="200">
              <template #default="scope">
                <el-button-group>
                  <el-button type="info" icon="el-icon-view" size="small" title="查看" @click="toView(scope.row, '1')" />
                  <el-button type="primary" icon="el-icon-edit" size="small" title="编辑"
                    v-if="$hasPermission('system:role:update')" @click="toView(scope.row)" />
                  <el-button type="danger" icon="el-icon-delete" size="small" title="删除"
                    v-if="$hasPermission('system:role:delete')" @click="del(scope.row)" />
                  <el-button type="success" icon="el-icon-coordinate" size="small" title="授权"
                    v-if="$hasPermission('system:role:grant-permission')" @click="toGrant(scope.row)" />
                </el-button-group>
              </template>
            </el-table-column>
          </template>
        </autumn-table>
      </div>
    </div>

    <el-dialog title="权限授权" v-model="showDialog" width="15%" :close-on-click-modal="false" @close="handleClose">
      <!-- 标签页 -->
      <div class="permission-scrollbar" style="height: 50vh;">
        <el-scrollbar>
          <el-tree ref="permissionTreeRef" node-key="id" show-checkbox :check-strictly="true" :props="{ label: 'name' }"
            :default-expanded-keys="permissionTree.expandedKeys" :data="permissionTree.data"
            :default-checked-keys="permissionTree.checkedKeys"></el-tree>
        </el-scrollbar>
      </div>
      <!-- 按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="grant">确 定</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import useTable from 'src/hooks/useTable'
import { $hasPermission, $confirmMsg, $convertTree } from 'src/hooks/useCommon'
import { pageRole, enableRole, disableRole, deleteRole, listCheckedPermission, grantPermission } from 'src/api/system/role'
import { listMenu } from 'src/api/system/menu'

const { selectNum, page, changeSelect } = useTable()

const mainTableRef = ref()
const router = useRouter()

// 查询权限
const permissionTree = reactive({
  data: [] as any,
  expandedKeys: [] as any,
  checkedKeys: [] as any
})
listMenu().then(({ data }) => {
  permissionTree.data = $convertTree(data)
  permissionTree.expandedKeys = [data[0].id]
})

// 分页查询
const queryInfo = reactive({
  code: '',
  name: '',
  isEnable: ''
})
const changePage = function (pageNumber: number, pageSize: number) {
  page.pageNumber = pageNumber
  page.pageSize = pageSize
  pageRole({ ...queryInfo, pageNumber, pageSize }).then(({ data }) => {
    page.data = data.list
    page.total = data.total
  })
}
const search = function () {
  changePage(1, 10)
}
search()

// 启/禁用角色
const changeEnabled = function (row: any) {
  const id = row.id
  const isEnable = row.isEnable
  if (isEnable) {
    enableRole(id).then(() => {
      search()
    })
  } else {
    disableRole(id).then(() => {
      search()
    })
  }
}

// 删除角色
const del = function (row: any) {
  const ids = [row.id]
  $confirmMsg('确认删除吗？', () => {
    deleteRole(ids).then(() => {
      search()
    })
  })
}

// 查看角色
const toView = function (row: any, type?: string) {
  const id = row.id
  router.push({
    path: type ? '/system/role/roleView' : '/system/role/roleForm',
    query: { id }
  })
}

// 菜单授权
const permissionTreeRef = ref()
const showDialog = ref<boolean>(false)
const grantRole = reactive({
  id: '',
  permissionIds: []
})
const toGrant = function (row: any) {
  const id = row.id
  grantRole.id = id
  listCheckedPermission(id).then(({ data }) => {
    permissionTree.checkedKeys = data
  })
  showDialog.value = true
}
const grant = function () {
  const permissionIds = permissionTreeRef.value.getCheckedKeys()
  if (!permissionIds || permissionIds.length === 0) {
    ElMessage.error('请选择授权权限')
    return
  }
  grantRole.permissionIds = permissionIds
  grantPermission(grantRole)
  showDialog.value = false
}
const handleClose = function () {
  grantRole.id = ''
  permissionTree.checkedKeys = []
  permissionTreeRef.value.setCheckedKeys([])
}

// 分配用户
const toUserView = () => {
  const selection = mainTableRef.value.$refs.dataTableRef.getSelectionRows()
  const id = selection[0].id
  router.push({
    path: '/system/role/grantUser',
    query: { id }
  })
}

</script>

<style lang="scss" scoped>
.permission-scrollbar {
  :deep(.el-scrollbar__wrap) {
    overflow-x: hidden !important;
  }
}
</style>
